package we.core.handlers;

import java.nio.channels.SocketChannel;

import java.util.HashMap;
import java.util.Map;

import we.core.bean.CDataContainer;
import we.core.bean.CRoom;
import we.core.bean.CUser;

import we.extension.CSystemEvent;

import org.json.JSONObject;


public class CDisconnectHandler extends CAbstractCoreHandler {
    public int handleEvent(SocketChannel channel, JSONObject data) {
        String username;
        CUser u = CDataContainer.instance().getUserByChannel(channel);
        if (u != null) {
            CDataContainer.instance().removeUser(u);
            CRoom r = CDataContainer.instance().getRoom(u.roomId);
            if (r != null)
                r.removeUser(u.username);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("eventName", CSystemEvent.SystemEventType.DISCONNECT);
            params.put("user", u);
            params.put("fromRoomId", u.roomId);
            CSystemEvent se = new CSystemEvent(this, params);
            dispatchSystemEvent(se);
        }
        return 0;
    }
}
